﻿using System;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web.Mvc;
using MvcForum.Net.Bussiness;
using MvcForum.Net.FileManager;

namespace MvcForum.Net.Controllers
{

    /*[ValidateAuthentication]*/
    public class FileController : BaseController
    {
        //
        // GET: /File/


        public ActionResult Upload(string uploadToPath)
        {

            var _sb = new StringBuilder();

            var uploadPath = FileHelpers.PathCombine(ForumContext.Configuration.UploadPath, uploadToPath);

            

            var _isAvatarUpload = Request["avatar"] == "1";

            string _url = Request["RemoteUrls"];
            try
            {
                // string[] _allowFileTypes = ConfigurationManager.AppSettings["ALLOW_FILE_TYPES"].Replace("*", string.Empty).Split(';');
                //FormsAuthenticationTicket _userTicket = FormsAuthentication.Decrypt(_encryptString);
                //if (!_userTicket.Expired && context.Request.Files.Count > 0)
                if (Request.Files.Count > 0 || !string.IsNullOrEmpty(_url))
                {

                    string _uploadToPath = Request["uploadToPath"];

                    bool _autoNameAndPath = false;

                    bool.TryParse(Request["autoNameAndPath"], out _autoNameAndPath);

                    if (string.IsNullOrEmpty(_uploadToPath))
                    {
                        _uploadToPath = uploadPath;
                    }



                    string _uploadPath = _autoNameAndPath
                                             ? FileHelpers.PathCombine(uploadPath, DateTime.UtcNow.ToString("yyyy/MM/dd"))
                                             : FileHelpers.PathCombine(uploadPath, _uploadToPath);

                    _uploadPath = Server.MapPath(_uploadPath);


                    // Create Path
                    FileHelpers.CreateFolder(_uploadPath);


                    if (!string.IsNullOrEmpty(_url))
                    {

                        var _urls = _url.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);

                        _sb.Append(string.Join(";", (from _s in _urls
                                                     let _fileName = string.Format("{0}{1}", DateTime.UtcNow.ToUnixTimestamp(), ".jpg")
                                                     where FileHelpers.Download(_s, Path.Combine(_uploadPath, _fileName))
                                                     select _fileName).ToArray()));


                    }
                    else
                    {
                        // loop through all the uploaded files
                        for (int j = 0; j < Request.Files.Count; j++)
                        {


                            var _uploadFile = Request.Files[j];


                            //  bool _allowUpload = _allowFileTypes.Any(fileType => fileType.ToLower() == _fileExt);
                            // Check allow upload with file extention

                            if (_uploadFile != null && _uploadFile.ContentLength > 0)
                            {
                                string _fileName = _uploadFile.FileName;
                                string _fileExt = Path.GetExtension(_fileName);
                                _fileName = string.Format("{0}{1}", DateTime.UtcNow.ToUnixTimestamp(), _fileExt);

                                string _outPath = Path.Combine(_uploadPath, _fileName);


                                if (ImageHelpers.IsGraphic(_fileName) && _isAvatarUpload)
                                {
                                    int _w = ForumContext.Configuration.AvatarWidth;
                                    int _h = ForumContext.Configuration.AvatarHeight;

                                    ImageHelpers.ResizeStream(_uploadFile.InputStream, _outPath, _w, _h, null, 0, 0);
                                }
                                else
                                {

                                    FileHelpers.Write(_uploadFile.InputStream, _outPath);

                                }

                            }

                            System.Threading.Thread.Sleep(1000);


                        }// en loop
                    }


                }
            }
            catch (Exception ex)
            {

                log.Error("Upload: " + ex);

             
                throw new IdentityNotMappedException(ex.ToString());
            }


            return Content(_sb.ToString());

        }

        
        /*public ActionResult Upload()
        {

            var _sb = new StringBuilder();

            var UploadPath = ForumContext.UserUploadPath;

            var _isAvatarUpload = Request["avatar"] == "1";

            string _url = Request["RemoteUrls"];
            try
            {
                // string[] _allowFileTypes = ConfigurationManager.AppSettings["ALLOW_FILE_TYPES"].Replace("*", string.Empty).Split(';');
                //FormsAuthenticationTicket _userTicket = FormsAuthentication.Decrypt(_encryptString);
                //if (!_userTicket.Expired && context.Request.Files.Count > 0)
                if (Request.Files.Count > 0 || !string.IsNullOrEmpty(_url))
                {

                    string _uploadToPath = Request["uploadToPath"];

                    bool _autoNameAndPath = false;

                    bool.TryParse(Request["autoNameAndPath"], out _autoNameAndPath);

                    if (string.IsNullOrEmpty(_uploadToPath))
                    {
                        _uploadToPath = UploadPath;
                    }


                    string _uploadPath = _autoNameAndPath
                                             ? FileHelpers.PathCombine(UploadPath, DateTime.UtcNow.ToString("yyyy/MM/dd"))
                                             : FileHelpers.PathCombine(UploadPath, _uploadToPath);

                    _uploadPath = Server.MapPath(_uploadPath);


                    // Create Path
                    FileHelpers.CreateFolder(_uploadPath);


                    if (!string.IsNullOrEmpty(_url))
                    {

                        var _urls = _url.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);

                        _sb.Append(string.Join(";", (from _s in _urls
                                                     let _fileName = string.Format("{0}{1}", DateTime.UtcNow.ToUnixTimestamp(), ".jpg")
                                                     where FileHelpers.Download(_s, Path.Combine(_uploadPath, _fileName))
                                                     select _fileName).ToArray()));


                    }
                    else
                    {
                        // loop through all the uploaded files
                        for (int j = 0; j < Request.Files.Count; j++)
                        {


                            var _uploadFile = Request.Files[j];


                            //  bool _allowUpload = _allowFileTypes.Any(fileType => fileType.ToLower() == _fileExt);
                            // Check allow upload with file extention

                            if (_uploadFile != null && _uploadFile.ContentLength > 0)
                            {
                                string _fileName = _uploadFile.FileName;
                                string _fileExt = Path.GetExtension(_fileName);
                                _fileName = string.Format("{0}{1}", DateTime.UtcNow.ToUnixTimestamp(), _fileExt);

                                string _outPath = Path.Combine(_uploadPath, _fileName);


                                if (ImageHelpers.IsGraphic(_fileName) && _isAvatarUpload)
                                {
                                    int _w = ForumContext.Configuration.AvatarWidth;
                                    int _h = ForumContext.Configuration.AvatarHeight;

                                    ImageHelpers.ResizeStream(_uploadFile.InputStream, _outPath, _w, _h, null, 0, 0);
                                }
                                else
                                {

                                    FileHelpers.Write(_uploadFile.InputStream, _outPath);

                                }

                            }

                            System.Threading.Thread.Sleep(150);


                        }// en loop
                    }


                }
            }
            catch (Exception ex)
            {

                Logging.Log("Upload: " + ex);

                Logging.Log(_url);

                throw new IdentityNotMappedException(ex.ToString());
            }


            return Content(_sb.ToString());

        }*/
        [HttpGet, HttpPost]
        public ActionResult Download()
        {
            var _sb = new StringBuilder();

            return Content(_sb.ToString());

        }


        public ActionResult Config()
        {
            var _sb = new StringBuilder();
            
            _sb.AppendFormat("focusPath = '{0}' ", Request.QueryString["target"]);
            _sb.AppendFormat("scriptManager='{0}' ",  ForumContext.Configuration.FileManagerScript);
            _sb.AppendFormat("thumbnailScript='{0}' ", ForumContext.Configuration.ThumbnailScript);
            _sb.AppendFormat("iconPrefix='{0}' ", ForumContext.Configuration.IconFileTypePath);
            _sb.AppendFormat("fileSizeLimit='0' ");
            _sb.Append("autoNameAndPath='1' ");
            _sb.Append("allowDelete='1' ");
            _sb.AppendFormat("fileTypes='{0}' ", ForumContext.UserInfo.Permissions.AllowFileTypes);
            _sb.AppendFormat("totalUploadSize='0' ");
            _sb.AppendFormat("maxUploadFiles='10' ");
            _sb.AppendFormat("fileTypeDescription='{0}' ", Server.UrlEncode(ForumContext.GetText(LanguageSection.FILE_MANAGER, "FILE_TYPE_DESCRIPTION")));
            _sb.Append("rememberLastPath='1' ");
            _sb.Append("clientCallbackFunction='$.FlexExplorer.insert' ");
            _sb.Append("clientSetCookieFunction='$.FlexExplorer.rememberLastPath' ");
            _sb.Append("returnFull='1' ");

            return Content(string.Format("<config {0} />",_sb), "text/xml");
        }

        [ValidateAuthentication]
        public ActionResult Manager()
        {
           ViewBag.SessionId = ForumContext.Encrypt(ForumContext.UserInfo.UserId, ForumContext.UserInfo.UserName);

            if (Request.IsAjaxRequest())
            {
                return PartialView("Manager");
            }

            return View();
        }

        [HttpPost]
        public ActionResult Manager(FormCollection form)
        {

            var _sessionId = Request["sessionId"];
            var _args = ForumContext.Decrypt(_sessionId);
            var action = Request["action"];
            var path = _args[0]; 
            if(!string.IsNullOrWhiteSpace(Request["path"]))
                path = FileHelpers.PathCombine(path, Request["path"]);
           
            var input = Request["input"];

            var _xml = "";

            switch (action)
            {
                case "folder":
                case "files":
                case "search":

                  _xml=  FetchItems(path);

                    break;

                case "upload":
                   return Upload(path);
                    break;

                case "del":
                    var _items = Request["items"].Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    FileHelpers.Delete(_items);

                    break;

                case "newdir":
                    FileHelpers.CreateFolder(input, path);
                    break;

                case "rename":

                    var _old = Request["oldname"];
                    FileHelpers.ReNameFileOrFolder(_old, input);

                    break;

                case "move":
                    bool _overwrite;
                    bool.TryParse(Request["overwrite"], out _overwrite);
                    var _itemsMove = Request["items"].Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    FileHelpers.Move(_itemsMove, path, _overwrite);

                    break;


            }

            return Content(_xml, "text/xml");

        }


        #region FetchItems
        protected string FetchItems(string path)
        {


            string[] _exts = null;
            var _allowType = Request["allowTypes"];

            if (!string.IsNullOrWhiteSpace(_allowType) && !string.IsNullOrWhiteSpace(FileHelpers.FileTypes[_allowType.ToLower()]))
            {
                _exts = FileHelpers.FileTypes[_allowType.ToLower()].Split(';');

            }

            bool _searchSubFolder;

            bool.TryParse(Request["searchInSub"], out _searchSubFolder);

            string _search = Request["search"];


            FileFilter _fileFilter = FileFilter.All;

            if (!string.IsNullOrWhiteSpace(_search))
            {
                _fileFilter = FileFilter.Files;
                _search = string.Format("*{0}*", _search);
            }

            if (string.IsNullOrWhiteSpace(_search))
                _search = "*.*";



            var _items = FileHelpers.FetchItems(path, _search, _exts, _searchSubFolder, _fileFilter);

            var _sb = new StringBuilder();

            
            _sb.Append("<root>");

            foreach (var _fileItem in _items)
            {

                string _icon = "none.gif";

                string _itemType = "none";

                // var _id = _fileItem.Created.Ticks;

                if (_fileItem.IsFolder)
                {
                    _icon = "folder.gif";
                    _itemType = "folder";
                }

                else if (ImageHelpers.IsGraphic(_fileItem.Name))
                {
                    _itemType = "img";
                }
                if (_fileItem.IsExistsIcon)
                {
                    _icon = string.Format("{0}.gif", _fileItem.Extension.Replace(".", ""));

                }

                _sb.AppendFormat("<item name=\"{0}\" type=\"{1}\" path=\"{2}\" icon=\"{3}\" extension=\"{4}\" />", Server.HtmlEncode(_fileItem.Name), _itemType, Server.HtmlEncode(_fileItem.FullName), _icon, _fileItem.Extension);


            }


            _sb.Append("</root>");

            return _sb.ToString();
        }


        #endregion



    }
}
